package com.util;

import org.apache.commons.beanutils.BeanUtilsBean;

import java.lang.reflect.InvocationTargetException;

/**
 * Description: 对象合并的工具类
 */
public class CombineBeansUtil {


    /**
     * 该方法是用于相同对象不同属性值的合并
     * 如果两个相同对象中同一属性都有值，targetBean中的值优先级更高
     * 如果sourceBean有值，targetBean没有，则采用sourceBean的值
     * 如果sourceBean没有值，targetBean有，则保留targetBean的值
     *
     * @param sourceBean 被提取的对象bean
     * @param targetBean 用于合并的对象bean
     */
    public static <T> void combineBean(T sourceBean, T targetBean) throws InvocationTargetException, IllegalAccessException {

        new BeanUtilsBean() {
            @Override
            public void copyProperty(Object dest, String name, Object value)
                    throws IllegalAccessException, InvocationTargetException {
                if (value != null) {
                    super.copyProperty(dest, name, value);
                }
            }
        }.copyProperties(targetBean, sourceBean);

    }


}
